﻿#!/bin/bash
set -e

# ==============================
# 配置
# ==============================
APPNAME="MinecraftEnchantCalculator"
VERSION="2.0.0"
ARCH="amd64"

# 当前脚本所在目录（即解压后的目录）
SRC_DIR="$(cd "$(dirname "$0")" && pwd)"

# 打包目标目录
PKG_DIR="$SRC_DIR/${APPNAME}_${VERSION}_${ARCH}"

# ==============================
# 准备目录
# ==============================
echo "==> 清理旧目录..."
rm -rf "$PKG_DIR"
mkdir -p "$PKG_DIR/DEBIAN"
mkdir -p "$PKG_DIR/usr/bin"
mkdir -p "$PKG_DIR/usr/lib/$APPNAME"
mkdir -p "$PKG_DIR/usr/share/applications"
mkdir -p "$PKG_DIR/usr/share/icons/hicolor/256x256/apps"

# ==============================
# 控制文件
# ==============================
echo "==> 创建 control 文件..."
cat > "$PKG_DIR/DEBIAN/control" <<EOF
Package: $APPNAME
Version: $VERSION
Section: utils
Priority: optional
Architecture: $ARCH
Maintainer: Your Name <you@example.com>
Description: $APPNAME
 A Minecraft enchant calculator built with Avalonia.
EOF

chmod 644 "$PKG_DIR/DEBIAN/control"

# ==============================
# 复制应用文件
# ==============================
echo "==> 复制应用文件..."
STAGING_DIR="$SRC_DIR/staging"
rm -rf "$STAGING_DIR"
mkdir -p "$STAGING_DIR"

# 复制发布文件（排除掉打包目录和 staging 自身）
for f in "$SRC_DIR"/*; do
    fname=$(basename "$f")
    if [[ "$fname" != $(basename "$PKG_DIR") && "$fname" != "staging" && "$fname" != $(basename "$0") ]]; then
        cp -r "$f" "$STAGING_DIR/"
    fi
done

# 放到 /usr/lib 下
cp -r "$STAGING_DIR"/* "$PKG_DIR/usr/lib/$APPNAME/"
rm -rf "$STAGING_DIR"

# 确保主程序可执行
chmod +x "$PKG_DIR/usr/lib/$APPNAME/$APPNAME"

# ==============================
# 创建启动器
# ==============================
echo "==> 创建启动器..."
cat > "$PKG_DIR/usr/bin/$APPNAME" <<EOF
#!/bin/bash
exec /usr/lib/$APPNAME/$APPNAME "\$@"
EOF
chmod +x "$PKG_DIR/usr/bin/$APPNAME"

# ==============================
# 桌面图标
# ==============================
echo "==> 创建桌面文件..."
cat > "$PKG_DIR/usr/share/applications/$APPNAME.desktop" <<EOF
[Desktop Entry]
Name=$APPNAME
Exec=$APPNAME
Icon=$APPNAME
Type=Application
Categories=Utility;
EOF

# 复制 PNG 图标
if [ -f "$PKG_DIR/usr/lib/$APPNAME/Assets/icon.png" ]; then
    cp "$PKG_DIR/usr/lib/$APPNAME/Assets/icon.png" \
       "$PKG_DIR/usr/share/icons/hicolor/256x256/apps/$APPNAME.png"
else
    echo "警告: 未找到 $PKG_DIR/usr/lib/$APPNAME/Assets/icon.png"
fi


# ==============================
# 打包
# ==============================
echo "==> 构建 deb 包..."
dpkg-deb --build --root-owner-group "$PKG_DIR"

echo "==> 完成!"
echo "生成的包: $PKG_DIR.deb"
